package pe.org.manuela.app.ui

import java.awt.*
import javax.swing.*
import pe.org.manuela.app.despachadores.*

static def cargar(sw, modificando) {
	
	def idInsumo = null
	
	def ingresarInsumo = {
		def params = [:]
		params.descripcion = sw.txtDescripcion.text
		params.estado = sw.cboActivo.selectedItem == "No" ? "I" : "A"
		InsumoDespachador.ingresarInsumo(params)
	}
	
	def modificarInsumo = {
		def params = [:]
		params.id = idInsumo
		params.descripcion = sw.txtDescripcion.text
		params.estado = sw.cboActivo.selectedItem == "No" ? "I" : "A"
		InsumoDespachador.modificarInsumo(params)
	}
	
	
	def dlgInsumo = sw.dialog(
		id: "dlgInsumo",
		owner: sw.frmInsumos, 
		title: "Insumo", 
		modal: true
		) {

			borderLayout()
			panel(constraints: BorderLayout.CENTER) {
				boxLayout(axis: BoxLayout.Y_AXIS)
				panel(preferredSize: [0, 10])
				panel() {
					boxLayout(axis: BoxLayout.X_AXIS)
					label(text: "Descripción:")
					textField(id: "txtDescripcion", columns: 20)
				}
				panel(preferredSize: [0, 10])
				panel() {
					boxLayout(axis: BoxLayout.X_AXIS)
					label(text: "Activo:", preferredSize: [85, 20])
					comboBox(id: "cboActivo", items: ["Sí", "No"] as Object[])
					panel(preferredSize: [40, 0])
				}
				panel(preferredSize: [0, 10])
			}
			panel(constraints: BorderLayout.SOUTH) {
				button(text: "Grabar", actionPerformed: {
					Thread.start {
						if (!modificando) {
							ingresarInsumo()
						} else {
							modificarInsumo()
						}
						dlgInsumo.dispose()
					}
				})
				button(text: "Cancelar", actionPerformed: {
					dlgInsumo.close()
				})
			}
		}
		
		dlgInsumo.pack()
		
		sw.cboActivo.selectedItem = 0
		
		if (modificando) {
			def tabla = sw.grdInsumos
			def insumo = tabla.getValueAt(tabla.selectedRow, 1)
			idInsumo = insumo.id
			sw.txtDescripcion.text = insumo.descripcion
			def mEstados = ["A": 0, "I": 1] 
			sw.cboActivo.selectedIndex = mEstados[insumo.estado]
		}		
		
		dlgInsumo.show()
}


